package com.lcq.study.concurrent;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName InterruptTest
 * @Description interrupt中断线程，并不是让线程结束，更准确的说法是通知线程结束当前状态，
 * 当线程正在sleep，interrupt可以将其唤醒（中断sleep），当线程正在运行，interrupt会添加中断标记，
 * 告知目标线程需要结束运行（中断运行）。
 * @Author lichuanqi
 * @Date 2022/5/23 10:18
 * @Version 1.0
 **/
public class InterruptTest {
    public static void main(String[] args) throws InterruptedException {
        //test1();

        test2();
    }
    /**
     * @Author lichuanqi
     * @Description 给正在运行的线程添加中断标记，线程内部自己处理标记
     * @Date 11:09 2022/5/23
     * @Param []
     * @return void
     **/
    private static void test2() throws InterruptedException {
        Thread thread1 = new Thread(new Run2());
        thread1.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            System.out.println("InterruptedException "+e.getMessage());
        }
        System.out.println("interrupt thread1");
        thread1.interrupt();
        thread1.join();
    }

    /**
     * @Author lichuanqi
     * @Description interrupt打断正在阻塞线程状态，抛出InterruptedException异常
     * @Date 10:40 2022/5/23
     * @Param []
     * @return void
     **/
    private static void test1() throws InterruptedException {
        Thread thread1 = new Thread(new Run1());
        thread1.run();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread1.interrupt();
        thread1.join();
    }


    static class Run1 implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println(""+i);
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    System.out.println("InterruptedException "+e.getMessage());
                    break;
                }
            }
        }
    }

    static class Run2 implements Runnable{
        @Override
        public void run() {
            while (true){
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("isInterrupted!!");
                    break;
                }
                System.out.println("hello");
            }
        }
    }
}
